package injection;

import domain.User;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;

/**
 * Autowire 方法注入
 * @author jackcfan
 * @date 2021/9/16
 */
public class AnnotationMethodInjectionTest {
    User user;
    UserHolder userHolder;

    /**
     * @Autowired 和 @Resource 修饰方法，方法内的参数自动注入
     * 方法名称无所谓，重要的方法参数是作为依赖注入进来的
     * */
    @Autowired
    public void initUserHold(UserHolder userHolder){
        this.userHolder = userHolder;
    }

    @Resource
    public void initUser(User user){
        this.user = user;
    }

    @Test
    public void test(){
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 注册 Configuration class 配置类
        applicationContext.register(this.getClass());

        // 启动 Spring 上下文
        applicationContext.refresh();

        AnnotationMethodInjectionTest annotation = applicationContext.getBean(this.getClass());
        System.out.println("userHolder>"+annotation.userHolder);
        System.out.println("user>"+annotation.user);

        applicationContext.close();
    }

    @Bean
    public User user(){
        User user = new User();
        user.setName("AnnotationFieldInjectionTest");
        user.setId(1L);
        return user;
    }

    @Bean
    public UserHolder userHolder(User user){
        return new UserHolder(user);
    }
}
